import { message } from 'antd';
import { routerRedux } from 'dva/router';
import {
  getListUserInfo,
  getDictList,
  getOrgInfo,
  queryOrgListByParentId,
  queryBaseRoleLike,
  insertUserInfo,
  queryUserInfoById,
  updateUserInfo,
  resetUserPwd,
  getDetailInfo,
  deleteUserInfo,
  enOrdisableUser,
  getQueryUserByOrgId,
  getCustList,
} from '@/services/authoritymanage';

export default {
  state: {
    formFieldsValue: {},
    expandForm: false,
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    dictData: {
      COMMON_ENABLED_STATUS: [],
      USER_TYPE: [],
      POST_TYPE: [],
    },
    // 所属公司下拉列表
    corpIdList: [],
    // 所属部门列表项
    provCityAreaList: [],
    roleList: [],
    // 修改页面信息
    updateInfo: {},
    action: 'add', // 区分新增或修改
    detailInfo: {},
    queryUserList: [],
    custList: [],
  },
  effects: {
    // 获取用户列表
    fetchDictList: [
      function* fetchDictList({ payload }, { call, put }) {
        const response = yield call(getDictList, payload);
        if (response.success) {
          yield put({
            type: 'getDict',
            payload: response.data,
          });
        } else {
          message.warning(`${response.message || '字典查询失败！'}`);
        }
      },
      { type: 'takeLatest' },
    ],
    *fetchListUserInfo({ payload }, { call, put }) {
      const response = yield call(getListUserInfo, payload);
      const {
        page: { currentPage, pageSizes },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize: pageSizes,
          },
        });
      } else {
        message.warning(`${response.message || '查询失败！'}`);
      }
    },
    fetchOrgInfo: [
      function* fetchOrgInfo({ payload }, { call, put }) {
        const response = yield call(getOrgInfo, payload);
        if (response.success) {
          yield put({
            type: 'getCorpIdList',
            payload: response.data,
          });
        } else {
          message.warning(`${response.message || '查询失败！'}`);
        }
      },
      { type: 'takeLatest' },
    ],
    // eslint-disable-next-line consistent-return
    *fetchOrgListByParentId({ payload }, { call, put }) {
      // type为1是所选公司，为2是所选部门
      const { corpId, type, isChild, orgId } = payload;
      const response =
        type === 1
          ? yield call(queryOrgListByParentId, { corpId })
          : yield call(queryOrgListByParentId, { orgId });

      if (response.success) {
        if (response.data && response.data.length === 0) {
          message.warning('暂无数据');
          return false;
        }
        if (isChild) {
          const provChildAreaList = response.data.map(item => ({
            label: item.name,
            value: item.orgId,
            isLeaf: item.leafFlag === 1,
          }));
          return provChildAreaList;
        }
        yield put({
          type: 'getOrgListByParentId',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '查询失败！'}`);
        return false;
      }
    },
    fetchBaseRoleLike: [
      function* fetchBaseRoleLike({ payload }, { call, put }) {
        const response = yield call(queryBaseRoleLike, payload);
        if (response.success) {
          yield put({
            type: 'updateModalData',
            payload: { roleList: response.data },
          });
        } else {
          message.warning(`${response.message || '查询失败！'}`);
        }
      },
      { type: 'takeLatest' },
    ],
    *addUserInfo({ payload }, { call, put }) {
      const response = yield call(insertUserInfo, payload);
      if (response.success) {
        yield put(
          routerRedux.replace({
            pathname: '/systemmanage/user/index',
          })
        );
      } else {
        message.warning(`${response.message || '新增失败！'}`);
      }
    },
    *updateUserInfo({ payload }, { call, put }) {
      const response = yield call(updateUserInfo, payload);
      if (response.success) {
        yield put(
          routerRedux.replace({
            pathname: '/systemmanage/user/index',
          })
        );
      } else {
        message.warning(`${response.message || '修改失败！'}`);
      }
    },
    // 查询修改信息
    fetchUserInfoById: [
      function* fetchUserInfoById({ payload }, { call, put }) {
        const response = yield call(queryUserInfoById, { userId: payload.userId });
        if (response.success) {
          if (payload.add) {
            yield put({
              type: 'updateModalData',
              payload: { roleList: response.data.roles },
            });
          } else {
            // 助理岗时，根据公司id查询所属用户
            if (response.data.postType === 3) {
              const resUser = yield call(getQueryUserByOrgId, {
                corpId: response.data.corpId,
                orgId: response.data.orgId,
                userType: 3,
                postTypes: [1, 2, 4],
              });
              if (resUser.success) {
                yield put({
                  type: 'updateModalData',
                  payload: { queryUserList: resUser.data },
                });
                // 根据所属用户查询所属用户权限列表
                const resRoles = yield call(queryUserInfoById, { userId: response.data.assoUser });
                if (resRoles.success) {
                  yield put({
                    type: 'updateModalData',
                    payload: { roleList: resRoles.data.roles },
                  });
                }
              }
            }
            // onsite时，角色根据系统
            if (response.data.postType === 4) {
              const resRoles = yield call(queryBaseRoleLike, {
                roleType: 3,
                sysIds: ['BS0000000003', 'BS0000000001'],
              });
              if (resRoles.success) {
                yield put({
                  type: 'updateModalData',
                  payload: { roleList: resRoles.data },
                });
              }
            }
            yield put({
              type: 'getUserInfo',
              payload: response.data,
            });
            if (Number(response.data.hasAssi) === 1) {
              message.warning(
                '当前用户下存在助理岗用户，请您及时更新助理岗用户的角色信息，避免出现角色不一致的情况'
              );
            }
          }
        } else {
          message.warning(`${response.message || '用户信息查询失败！'}`);
        }
      },
      { type: 'takeLatest' },
    ],
    *resetUserPwd({ payload }, { call }) {
      const response = yield call(resetUserPwd, payload);
      return response;
    },
    *fetchDetailInfo({ payload }, { call, put }) {
      const response = yield call(getDetailInfo, payload);
      if (response.success) {
        yield put({
          type: 'getUserDetailInfo',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '用户信息查询失败！'}`);
      }
    },
    *enOrdisableUser({ payload }, { call }) {
      const response = yield call(enOrdisableUser, payload);
      return response;
    },
    *deleteUserInfo({ payload, callback }, { call }) {
      const response = yield call(deleteUserInfo, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // zj
    *fetchQueryUserByOrgId({ payload }, { call, put }) {
      const response = yield call(getQueryUserByOrgId, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: { queryUserList: response.data },
        });
      } else {
        message.warning(`${response.message || '查询失败！'}`);
      }
    },
    *fetchCustList({ payload }, { call, put }) {
      const response = yield call(getCustList, payload);
      if (response.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            custList: Array.isArray(response.data)
              ? response.data.map(item => ({
                  groupName: item.name.concat('/').concat(item.suppName),
                  custId: item.custId,
                }))
              : [],
          },
        });
      } else {
        message.warning(`${response.message || '查询失败！'}`);
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 获取字典
    getDict(state, { payload }) {
      return {
        ...state,
        dictData: { ...state.dictData, ...payload },
      };
    },
    // 获取公司下拉选项
    getCorpIdList(state, { payload }) {
      return {
        ...state,
        corpIdList: payload,
      };
    },
    // 获取所属部门下拉项
    getOrgListByParentId(state, { payload }) {
      // leafFlag 1:叶子节点
      const provCityAreaList = payload.map(item => ({
        label: item.name,
        value: item.orgId,
        isLeaf: item.leafFlag === 1,
      }));
      return {
        ...state,
        provCityAreaList,
      };
    },
    // 获取修改信息
    getUserInfo(state, { payload }) {
      const obj = {};
      const arr = [
        'userName',
        'userIdCard',
        'mobile',
        'email',
        'loginName',
        'corpId',
        'orgId',
        'remark',
        'userId',
        'assoUser',
      ];
      Object.keys(payload).forEach(key => {
        if (arr.indexOf(key) > -1) {
          obj[key] = payload[key];
        }
        if (key === 'postType') {
          obj[key] = `${payload[key]}`;
        }
        if (key === 'roles') {
          const pdArr = [];
          payload[key].forEach(item => {
            pdArr.push(item.roleId);
          });
          obj[key] = pdArr;
        }

        if (key === 'orgList') {
          let pdStr = '';
          payload[key].forEach(item => {
            if (pdStr) {
              pdStr = `${pdStr}/${item.name}`;
            } else {
              pdStr = `${item.name}`;
            }
          });
          obj.orgIdName = pdStr;
        }
        if (key === 'orgId') {
          // obj.hiddenOrgId = payload[key];
        }
        if (key === 'assoCustList') {
          const pdArr = [];
          const pdArrId = [];
          payload[key].forEach(item => {
            pdArr.push({
              custId: item.custId,
              groupName: item.name.concat('/').concat(item.suppName),
            });
            pdArrId.push(item.custId);
          });
          obj.assoCusts = pdArrId;
          // eslint-disable-next-line no-param-reassign
          state.custList = pdArr;
        }
      });
      return {
        ...state,
        updateInfo: obj,
        assoUserFlag: Number(payload.postType) === 3,
        assoCustsFlag: Number(payload.postType) === 4,
      };
    },
    // 获取详情页信息
    getUserDetailInfo(state, { payload }) {
      let orgList = '';
      if (payload.orgList) {
        payload.orgList.forEach(item => {
          if (orgList) {
            orgList = `${orgList}/${item.name}`;
          } else {
            orgList = `${item.name}`;
          }
        });
      }
      const roleArr = [];
      if (payload.roles) {
        payload.roles.forEach(item => {
          roleArr.push(item.roleName);
        });
      }
      const roles = roleArr.join(',');

      const assoCustListArr = [];
      if (payload.assoCustList) {
        payload.assoCustList.forEach(item => {
          assoCustListArr.push(item.name.concat('/').concat(item.suppName));
        });
      }
      const assoCustsName = assoCustListArr.join('，');

      return {
        ...state,
        detailInfo: { ...payload, orgList, roles, assoCustsName },
        assoUserFlag: Number(payload.postType) === 3,
        assoCustsFlag: Number(payload.postType) === 4,
      };
    },
    updateModalData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    updateModalClearFrom(state, { payload }) {
      return {
        ...state,
        updateInfo: { ...state.updateInfo, ...payload },
      };
    },
    // zj
  },
};
